/* 随机打乱数组 */
Array.prototype.shuffle = function () {
  let len = this.length;
  let i = 0;
  while (i < len) {
    let rad = Math.floor(Math.random() * len);
    let t = this[i];
    this[i] = this[rad];
    this[rad] = t;
    i++;
  }
  return this;
};

function getStyle(obj, attr) {
  if (obj.currentStyle) {
    console.log(obj.currentStyle);
    return obj.currentStyle[attr];
  } else {
    return getComputedStyle(obj, false)[attr];
  }
}

function getPussInt(obj, attr) {
  return parseInt(getStyle(obj, attr));
}

function swapArr(arr, first, last) {
  // 在last处删除一项，并添加 arr[first];返回值是一个被删除的数组
  arr[first] = arr.splice(last, 1, arr[first])[0];
  return arr;
}

class Puzzle {
  constructor() {
    this.dom = document.getElementById("game_wrapper");
    this.btn = document.getElementsByTagName("button")[0];
    this.counter = document.getElementById("count");
    this.btnClick();
  }

  // 渲染到页面
  writeHtml() {
    let count = 5;
    this.dom.innerHTML = "";
    for (let i = 0; i < this.arr.length; i++) {
      let oLi = document.createElement("li");
      oLi.classList.add("game-box-" + this.arr[i]);
      oLi.setAttribute("data-num", i);
      let row = i % this.level;
      let col = Math.floor(i / this.level);
      oLi.style.left = row * 100 + count * row + "px";
      oLi.style.top = col * 100 + count * col + "px";
      if (i == this.arr.length - 1) {
        oLi.classList.add("active");
      }
      this.dom.appendChild(oLi);
    }
  }

  // 绑定点击事件
  btnClick() {
    this.btn.addEventListener("click", () => {
      this.init();
      let flag = this.dom.classList.contains("on");
      if (!flag) {
        this.dom.classList.add("on");
      }
    });
  }

  // 绑定点击事件
  bindClick() {
    let flag = true;
    let timer = null;
    this.dom.addEventListener("click", (e) => {
      if (flag) {
        flag = false;
        if (timer) clearTimeout(timer);
        let el = e.target;
        let ol = document.getElementsByClassName("active")[0];
        if (el.tagName == "LI") {
          // 如果点击空的那个，什么也不操作
          let num = el.dataset.num;
          console.log(this.len);
          if (num != this.len - 1) {
            this.swap(el, ol);
            this.isWin(this);
          }
        }

        // 预防点击过快
        timer = setTimeout(() => {
          flag = true;
        }, 500);
        return;
      }
    });
  }

  swap(el, ol) {
    let dom = {
      left: getPussInt(el, "left"),
      top: getPussInt(el, "top"),
      locl: el.dataset.num,
    };
    let active = {
      left: getPussInt(ol, "left"),
      top: getPussInt(ol, "top"),
      locl: ol.dataset.num,
    };

    let left = Math.abs(dom.left - active.left);
    let top = Math.abs(dom.top - active.top);
    // 只有相邻的才可以互换位置
    if ((left < 200 && top < 100) || (left < 100 && top < 200)) {
      el.style.left = active.left + "px";
      el.style.top = active.top + "px";
      ol.style.left = dom.left + "px";
      ol.style.top = dom.top + "px";
      swapArr(this.arr, +dom.locl, +active.locl);
      // 两个dom互换位置
      this.count++;
      this.counter.innerHTML = this.count;
    }
  }

  // 判断游戏是否胜利
  isWin() {
    // 判断 data-num顺序是否是 1-9；
    if (this.arr[this.arr.length - 1] === 9) {
      let flag = this.arr.every((e, i) => {
        return e === i + 1;
      });
      if (flag) alert("赢了");
    }
  }

  init() {
    // 初始化数据
    this.count = 0;
    this.level = 3;
    this.blockNum = Math.pow(this.level, 2);
    this.arr = [1, 2, 3, 4, 5, 6, 7, 8];
    this.arr.shuffle();
    this.arr.push(this.arr.length + 1);
    this.len = this.arr.length;

    // 初始化渲染
    this.writeHtml();
    this.bindClick();
  }
}

let puzzle = new Puzzle();
